const LabelModel = require('../mongoModel/lableModel')
const articleModel = require('../mongoModel/articleModel')
const visitsModel = require("../mongoModel/visitsModel")
const service = {
  // 创建对应标签
  addLabel (labelName) {
    return LabelModel.create({
      labelName,
      createTime: new Date(),
    })
  },
  // 查找对应标签
  findLabel () {
    return LabelModel.find()
  },
  // 删除对应标签
  delLabel (id) {
    return LabelModel.deleteOne({ _id: id })
  },
  // 添加对应文章
  addArticle (title, info, articleType, bg) {
    return articleModel.create({
      title,
      info,
      articleType,
      bg,
      createTime: Date.now(),
    })
  },
  // 修改对应文章
  updateArticle (_id, where, bg) {
    return articleModel.updateOne(
      { _id },
      {
        ...where,
        bg,
      }
    )
  },
  // 查找对应的文章片数
  findArticleSingle (where) {
    return articleModel.find({ articleType: where })
  },
  // 查找前台对应文章分页
  async getAllList (page, limite, where = {}) {
    // 获取到表总数
    // {'articleType': {$ne: "草稿"} 忽略articleType 等于草稿的时候
    let num = await articleModel
      .find({ ...{ articleType: { $ne: '草稿' }, ...where } })
      .count()
    // 获取到数据根据goodsPrice的顺序正序排序跳过(page - 1) * limite 条 要limit 条数据
    let data = await articleModel
      .find({ ...{ articleType: { $ne: '草稿' }, ...where } })
      .skip((page - 1) * limite)
      .sort({ createTime: -1 })
      .limit(limite)
    return { num, data }
  },
  // 查找后台对应文章分页
  async findArticleendList (page, limite, where = {}) {
    // 获取到表总数
    let num = await articleModel.find(where).count()
    // 获取到数据根据goodsPrice的顺序正序排序跳过(page - 1) * limite 条 要limit 条数据
    let data = await articleModel
      .find(where)
      .skip((page - 1) * limite)
      .sort({ createTime: -1 })
      .limit(limite)
    return { num, data }
  },
  // 删除对应的文章
  async delArticle (id) {
    return articleModel.deleteOne({ _id: id })
  },
  // 查找对应的文章
  async findArticleSingle1 (id) {
    return articleModel.find({ _id: id }).catch((err) => err)
  },
  // 查找后端全部数据
  async endfinAll () {
    return { articleCount: await articleModel.find().count() }
  },
  // 获取用户访问量
  getVists () {
    return visitsModel.find()
  }
}

module.exports = service
